from BaseTest import *
from BrowserManager import *
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException


class WebUIBaseTest(BaseTest):

    def __init__(self, methodName='runTest', driverType='Firefox'):
        print('init')
        self._browserType = driverType
        self._browserManager = BrowserManager(self._browserType)
        self.driver = None
        super(__class__, self).__init__(methodName)

    def setUp(self):
        self.driver = self._browserManager.start()
        self.driver.implicitly_wait(30)
        self.verificationErrors = []
        self.accept_next_alert = True

    def is_element_present(self, how, what):
        try:
            self.driver.find_element(by=how, value=what)
        except NoSuchElementException as e:
            return False
        return True

    def is_alert_present(self):
        try:
            self.driver.switch_to.alert()
        except NoAlertPresentException as e:
            return False
        return True

    def close_alert_and_get_its_text(self):
        try:
            alert = self.driver.switch_to.alert()
            alert_text = alert.text
            if self.accept_next_alert:
                alert.accept()
            else:
                alert.dismiss()
            return alert_text
        finally:
            self.accept_next_alert = True

    def tearDown(self):
        self._browserManager.shutdown()
        self.assertEqual([], self.verificationErrors)


if __name__ == "__main__":
    unittest.main()
